﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.Admin.Application.Service;
using Windows.Admin.Domain;
using Windows.Admin.Infrastructure.EFCore;
using Windows.Admin.Infrastructure.EFCore.Extensions;
using Windows.Application.Share;
using Windows.FileStorage.Contract;
using Windows.Infrastructure.Share;
using Windows.Infrastructure.Share.Extensions;
using Windows.Infrastructure.Share.Security;
using Windows.Infrastructure.Share.Tools;
using Windows.SeedWord;

namespace Windows.Admin.Application
{
    public class OrganizationService : IOrganizationService
    {
        private readonly IMapper _mapper;
        //private readonly ICache _cache;
        private readonly AdminDbContext _db;
        private readonly IAttachmentGrpcService _attachmentGrpcSvc;
        public OrganizationService(IMapper mapper, AdminDbContext db, IAttachmentGrpcService attachmentGrpcSvc)
        {
            _mapper = mapper;
            _db = db;
            _attachmentGrpcSvc = attachmentGrpcSvc;
        }
        /// <summary>
        /// 获取非岗位的组织机构
        /// </summary>
        /// <returns></returns>
        public async Task<List<OrganizationTreeResponse>> GetNoPostOrganization()
        {
            var list = await _db.Organization.ToListAsync();
            return BuildModuleTree(list, null);
        }
        /// <summary>
        /// 组织机构视图
        /// </summary>
        /// <returns></returns>
        public async Task<List<OrganizationTreeResponse>> Query()
        {
            var list = await _db.Organization.ToListAsync();
            return BuildModuleTree(list, null);
        }
        /// <summary>
        /// 获取id的组织机构详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<OrganizationResponse> Detail(int id)
        {
            var model = await _db.Organization.FindByIdAsync(id);
            return _mapper.Map<OrganizationResponse>(model);
        }
        /// <summary>
        /// 组织机构保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(OrganizationSaveRequest request)
        {
            if (_db.Organization.Count(x => x.Name.ToLower() == request.Name && x.Id != request.Id) > 0)
                throw new ApiException("组织机构名称已存在!");
            //string type = "";
            //if (request.PId != null)
            //{
            //    type = await _db.Organization.Where(x => x.Id == request.PId).Select(s => s.Type).FirstOrDefaultAsync();
            //}
            //if (request.Type <= type)
            //{
            //    throw new ApiException("不能添加到小于或同级的组织机构下!");
            //}

            if (request.Id == null)
            {
                Organization model = _mapper.Map<Organization>(request);
                await _db.Organization.AddAsync(model);
            }
            else
            {
                Organization? model = await _db.Organization.FindByIdAsync(request.Id.Value);
                if (model == null)
                    throw new ApiException("组织机构不存在!");
                request.PId = request.PId;
                model.Name = request.Name;
                request.Type = request.Type;
                request.Telephone = request.Telephone;
                request.Fax = request.Fax;
                request.Email = request.Email;
                request.Sort = request.Sort;
                model.Name = request.Name;
                model.Remark = request.Remark;
            }
            await _db.SaveChangesAsync();
        }
        protected List<OrganizationTreeResponse> BuildModuleTree(List<Organization> organizations, long? pId)
        {
            List<OrganizationTreeResponse> list = (from d in organizations
                                             where d.PId == pId
                                             orderby d.Sort
                                             select d into x
                                             select new OrganizationTreeResponse
                                             {
                                                 Id = x.Id,
                                                 PId = x.PId,
                                                 Type = x.Type,
                                                 Name = x.Name,
                                                 Telephone = x.Telephone,
                                                 Fax = x.Fax,
                                                 Email = x.Email,
                                                 Sort = x.Sort,
                                                 Remark = x.Remark,
                                                 CreatedBy = x.CreatedBy,
                                                 CreatedByName = x.CreatedByName,
                                                 CreatedOn = x.CreatedOn,
                                                 UpdatedBy = x.UpdatedBy,
                                                 UpdatedByName = x.UpdatedByName,
                                                 UpdatedOn = x.UpdatedOn,
                                                 Children = BuildModuleTree(organizations, x.Id)
                                             }).ToList();
            return list;
        }
    }
}
